package Threads.ReentrantLock;

import java.util.concurrent.locks.ReentrantLock;

public class Philosopher_reentlock {
    class Chopstick extends ReentrantLock {
        String name;
        public Chopstick(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return "筷子{" + name + '}';
        }
    }
    class Philosopher extends Thread {
        Chopstick left;
        Chopstick right;
        public Philosopher(String name, Chopstick left, Chopstick right) {
            super(name);
            this.left = left;
            this.right = right;
        }
        @Override
        public void run() {
            while (true) {
                // 尝试获得左手筷子
                if (left.tryLock()) {
                    try {
                        // 尝试获得右手筷子
                        if (right.tryLock()) {
                            try {
                                eat();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } finally {
                                right.unlock();
                            }
                        }
                    } finally {
                        left.unlock();
                    }
                }
            }
        }
        private void eat() throws InterruptedException {
            System.out.println("eatting--");
            Thread.sleep(1000);
        }
    }
}
